<%@ page language="java" contentType="image/jpeg" pageEncoding="UTF-8" buffer="none" %>
<%@ page trimDirectiveWhitespaces="true" %>
<%@ page contentType="image/jpeg" %>
<%@ page import="java.awt.*,java.awt.image.*,java.io.*,javax.imageio.*,javax.servlet.*,javax.servlet.http.*,java.util.*" %>
<%
  // 生成四位数验证码
  Random random = new Random();
  String captcha = String.valueOf(1000 + random.nextInt(9000));

  // 将验证码保存到会话中
  session = request.getSession();
  session.setAttribute("captcha", captcha);

  // 创建图片
  int width = 120;
  int height = 40;
  BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  Graphics g = image.getGraphics();
  g.setColor(Color.WHITE);
  g.fillRect(0, 0, width, height);
  g.setColor(Color.BLACK);
  g.setFont(new Font("Arial", Font.BOLD, 24));
  g.drawString(captcha, 25, 30);
  g.dispose();
  // 设置响应类型为JPEG
  response.setContentType("image/jpeg");
  // 禁止缓存
  response.setHeader("Pragma", "No-cache");
  response.setHeader("Cache-Control", "no-cache");
  response.setDateHeader("Expires", 0);

  // 输出图片
  ImageIO.write(image, "JPEG", response.getOutputStream());
%>
